import {  createSlice } from '@reduxjs/toolkit'
import customRouters from "@/router/index"; 

let initialState = {
    permissionRouters: []
}
const judge = ( roles, authority ) => roles.some( o => authority.includes(o) )

const getPermissionRouters = ( customRouters, roles ) => {
    return customRouters.filter( o => !o.meta.authority || (o.meta.authority && o.meta.authority.length && judge(roles, o.meta.authority ) )).map( ( item ) => {
        item = Object.assign({}, item)
        if( item.children && item.children.length) {
            item.children = getPermissionRouters( item.children, roles )
        }
        return item
    } )
}

//遍历把所有的path拿到
const allPath = ( permissionRouters, allPathArr ) => {
    permissionRouters.forEach(o => {
        if( o.children && o.children.length ) {
            allPath( o.children, allPathArr )
        }
        allPathArr.push( o.path )
    });
}


const permissionSlice = createSlice({
    name: 'permission',
    initialState,
    reducers: {
        permissionFilter( state, action ) {
            
            const roles = action.payload

            let permissionRouters = getPermissionRouters( customRouters, roles )

            let allPathArr = []

            allPath(permissionRouters, allPathArr)

            console.log('allPath', allPathArr)
            
            state.permissionRouters = allPathArr

        }
    }
})

export const  { permissionFilter  } = permissionSlice.actions

export default permissionSlice.reducer